<style scoped>
</style>
<template>
  <van-field v-bind="$attrs"
             :placeholder="placeholder"
             :model-value="content"
             readonly
             :is-link="!is_info"
             @click="show_select"  >
    <template #extra>
      <input v-if="!is_info" type="hidden" :name="name" :value="modelValue">
    </template>
  </van-field>
</template>

<script>
import s94 from "s94-js";
import {decode_config} from "@/js/s94_tool.js";
import {select_option} from "@/components/tool/select_option.vue";

export default {
  name: "select_one",
  props: {
    name: String,
    modelValue: [String,Number],
    config: [String,Object],
    placeholder: String,
    is_info: Boolean,
  },
  emits: ['update:modelValue','change'],
  data(){
    return {
      need_display: true, //定义当modelValue变动时是否需要渲染，用来阻止当前组件变动 modelValue 后重新渲染
      options: [],
      content: "",
      value_arr: [],
      option_arr: [],
    }
  },
  methods: {
    set_content(){
      let content_arr = [];
      for (let i = 0; i < this.value_arr.length; i++) {
        let op = this.option_arr[i] || {};
        content_arr.push(op.content)
      }
      this.content = content_arr.join(" / ");
    },
    display(){
      let options = decode_config(this.config);
      let val = s94.to_string(this.modelValue);
      this.value_arr = [];
      this.option_arr = [];

      let indexs = [];
      s94.eachloop(options, 'children', (row,k,obj,ks)=>{
        if (row.children && row.children.length) return true;
        if (row.value === val){
          indexs = ks;
          return false;
        }
      })
      let cache = options;
      indexs.forEach((i)=>{
        this.value_arr.push(cache[i].value)
        this.option_arr.push(cache[i]);
        cache = cache[i].children;
      })
      this.set_content();
    },
    show_select(){
      if (this.is_info) return;
      select_option(this.config, this.modelValue, this.label).then((value)=>{
        let _this = select_option._this;
        this.value_arr = _this.value_arr;
        this.option_arr = _this.option_arr;
        let val = _this.value;
        this.need_display = false;
        setTimeout(()=>{this.need_display=true},10)
        this.$emit('update:modelValue', val);
        this.$emit('change', val);

        this.set_content();
      })
    },
  },
  watch: {
    config(v){
      this.display();
    },
    modelValue(){
      if (this.need_display) this.display();
    },
  },
  mounted() {
    this.display();
  }
}
</script>